package com.rdxer.config;


import com.rdxer.core.security.JWTAuthenticationFilter;
import com.rdxer.core.security.SecurityConfig;
import com.rdxer.core.debug.HTTPLogFilter;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;


@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class AppSecurityConfig extends SecurityConfig {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .csrf()
                .disable();
        http.rememberMe().disable();
        // 禁用缓存
        http.headers().cacheControl().disable();
        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        ;
        http.logout().disable();

        http.authorizeRequests()
                // 任何  OPTIONS 放行
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                // 任何  OPTIONS 放行 end

                .antMatchers("/login").permitAll()
                .antMatchers("/signup").permitAll()

                .antMatchers("/test/*").permitAll()
                .antMatchers("/test2/*").permitAll()

                .antMatchers("/init").permitAll()
                .antMatchers("/init/*").permitAll()
                .antMatchers("/initwf").permitAll()

                .antMatchers("/client/**").permitAll()

//                .antMatchers("/admin/**").hasRole("Admin")

                // swagger start
                .antMatchers("/swagger-ui.html").permitAll()
                .antMatchers("/docs.html").permitAll()
                .antMatchers("/swagger-resources/**").permitAll()
                .antMatchers("/images/**").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/v2/api-docs").permitAll()
                .antMatchers("/configuration/ui").permitAll()
                .antMatchers("/configuration/security").permitAll()
                // swagger end


                .anyRequest().authenticated()
//        new JWTAuthenticationFailureHandler(result)
        // 任何 请求都需要进行 身份验证
        ;

//        http.addFilter(new JWTLoginFilter(authenticationManager(),jwtConfiguration))
        http.addFilter(new JWTAuthenticationFilter(authenticationManager(), userDetailsService, jwtConfiguration));

        http.addFilterBefore(new HTTPLogFilter(), BasicAuthenticationFilter.class);


    }
}
